using AvaloniaMaidVSIX.Models;
using EnvDTE;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AvaloniaMaidVSIX.Helpers
{
    public static class VSHelper
    {
        public static ProjectItemInfo GetSelectedItemInfoInSolutionExplorerCs(EnvDTE80.DTE2 dte)
        {
            var toolWindow = dte.ToolWindows;

            var solutionExplorer = toolWindow.SolutionExplorer;

            var selectedItems = (solutionExplorer.SelectedItems as IEnumerable).OfType<UIHierarchyItem>().Select(i => i.Object).OfType<ProjectItem>();
            var selectedItem = selectedItems.FirstOrDefault();

            if (selectedItem == null) return null;

            var project = selectedItem.ContainingProject;
            var projectFullName = project.FullName;
            var itemPath = selectedItem.FileNames[0];

            if (itemPath.EndsWith("axaml") || itemPath.EndsWith("xaml"))
            {
                var codeBehindPath = itemPath + ".cs";
                if (File.Exists(codeBehindPath)) return new ProjectItemInfo(projectFullName, codeBehindPath);
            }

            return new ProjectItemInfo(projectFullName, itemPath);
        }

        public static ProjectItemInfo GetCurrentEditItemInfo(EnvDTE80.DTE2 dte)
        {
            var projectItem = dte.ActiveDocument.ProjectItem;
            var project = projectItem.ContainingProject;
            var projectFullName = project.FullName;
            if (string.IsNullOrWhiteSpace(projectFullName)) return null;

            var itemPath = projectItem.FileNames[1];

            return new ProjectItemInfo(projectFullName, itemPath);
        }

        public static SelectionProjectItemInfo GetSelectionItemInfo(EnvDTE80.DTE2 dte)
        {
            var projectItem = dte.ActiveDocument.ProjectItem;
            var project = projectItem.ContainingProject;
            var projectFullName = project.FullName;
            var itemPath = projectItem.FileNames[0];
            var selelction = dte.ActiveDocument.Selection as TextSelection;
            var selectionStartIndex = selelction.ActivePoint.VirtualCharOffset;

            projectItem.Save();

            var textDocument = dte.ActiveDocument as TextDocument;
         

            return new SelectionProjectItemInfo(projectFullName, itemPath)
            {
                SelectionText = selelction.Text,
                TextSelection = selelction,
            };
        }

    }
}
